package leetcode


fun main(args: Array<String>) {
    println(`46_3SumClosest`().threeSumClosest(intArrayOf(0,0,0), 1))
}

class `46_3SumClosest` {

    fun threeSumClosest(nums: IntArray, target: Int): Int {

        var result = 0
        nums.sort()

        var i = 0
        var j = 0

        var diff = Int.MAX_VALUE
        while (i < nums.size - 2) {
            var left = i + 1
            var right = nums.size - 1
            val restSum = target - nums[i]

            while (left < right) {
                val leftValue = nums[left]
                val rightValue = nums[right]
                val sum = leftValue + rightValue
                if (Math.abs(sum - restSum) < diff) {
                    result = sum + nums[i]
                    diff = Math.abs(sum - restSum)
                } else {
                    if (sum - restSum > 0) {//右指针左移
                        while (nums[right] == rightValue && left < right)
                            right--
                    } else {
                        while (nums[left] == leftValue && left < right)
                            left++
                    }
                }
            }

            i++
        }
        return result
    }

}